package org.shunfeng.controller;

import org.shunfeng.pojo.Company;
import org.shunfeng.pojo.Delivery;
import org.shunfeng.pojo.SysUser;
import org.shunfeng.service.CompanyService;
import org.shunfeng.service.DeliveryListService;
import org.shunfeng.service.impl.CompanyServiceImpl;
import org.shunfeng.service.impl.DeliveryListServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

@WebServlet("/delivery/list")
public class DeliveryListController extends HttpServlet {
    private DeliveryListService deliveryListService = new DeliveryListServiceImpl();
    private CompanyService companyService = new CompanyServiceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("***************************");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("**********doGet*****************");
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        try {
        SysUser sysUser = (SysUser) req.getSession().getAttribute("user");
        Integer uId = sysUser.getId();
        System.out.println("uid = " + uId);

            List<Delivery> deliveryList =  deliveryListService.queryDeliveryListByUseId(uId);
            List<Company> companies = companyService.queryAllCompany();
            HashMap<Integer, Company> companyMap = new HashMap<>();

            for(Company company: companies){
                companyMap.put(company.getId(), company);
            }
            for (Delivery delivery : deliveryList){
                delivery.setCompany(companyMap.get(delivery.getCompanyId()));
            }
            req.setAttribute("deliveryList", deliveryList);
            req.getRequestDispatcher("/list.jsp").forward(req, resp);
//            for (Delivery delivery : deliveryList) {
//                System.out.println(delivery.toString());
//            }
        } catch (SQLException e) {
            System.out.println(e.toString());
            throw new RuntimeException(e);
        }

    }
}
